<script>
import { api } from '@/api';
import { Button, Field, Form, Toast } from 'vant';

export default {
  components: {
    Form,
    Field,
    Button
  },
  computed: {
  },
  data() {
    return {
      oldPassword: '',
      newPassword: '',
      confirmNewPassword: ''
    }
  },
  methods: {
    async onSubmit(data) {
      const res = await api.account.changePassword({
        oldPwd: data.oldPassword,
        newPwd: data.newPassword
      })

      if (res.success) {
        Toast.success({ message: '修改成功' })
        this.oldPassword = this.newPassword = this.confirmNewPassword = ''
      } else {
        Toast.fail({ message: res.data ?? '修改失败' })
      }
    }
  },
}
</script>

<template>
  <div class="change-password-container">
    <Form @submit="onSubmit">
      <Field v-model="oldPassword" label="旧密码" name="oldPassword" type="password" placeholder="请输入旧密码" size="large" autocomplete="oldPassword"
        :rules="[{ required: true, message: '请填写旧密码' }]" />
      <Field v-model="newPassword" label="新密码" name="newPassword" type="password" placeholder="请输入新密码" size="large" autocomplete="newPassword"
        :rules="[{ required: true, message: '请填写新密码' }]" />
      <Field v-model="confirmNewPassword" label="再次确认" name="confirmNewPassword" type="password" placeholder="请再次输入新密码" size="large" autocomplete="confirmNewPassword"
        :rules="[
          { required: true, message: '请再次填写新密码' },
          { validator: (val) => val === this.newPassword, message: '两次密码不一致' }
        ]" />
      <div class="submit-button-container">
        <Button round block size="large" type="primary" native-type="submit">
          修改密码
        </Button>
      </div>
    </Form>
  </div>
</template>

<style lang="less" scoped>
.change-password-container {
  .submit-button-container {
    padding: 0 10px;
    margin-top: 40px;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
}
</style>
